#会员信息视图文件
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.paginator import Paginator

from myadmin.models import Member
from datetime import datetime
import time

# ==============后台会员信息管理======================
# 浏览会员信息
def index(request, pIndex=1):
    mod = Member.objects
    list = mod.filter(status__lt=9)
    mywhere = []
    # 获取、判断并封装关keyword键搜索
    kw = request.GET.get("keyword", None)
    if kw:
        # 查询店铺名称中只要含有关键字就可以
        list = list.filter(nickname__contains=kw)
        mywhere.append("keyword=" + kw)
    #执行分页处理
    pIndex = int(pIndex)
    page = Paginator(list, 5)  #以5条每页创建分页对象
    maxpages = page.num_pages  #最大页数
    #判断页数是否越界
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)  #当前页数据
    plist = page.page_range  #页码数列表

    #封装信息加载模板输出
    context = {
        "memberlist": list2,
        'plist': plist,
        'pIndex': pIndex,
        'maxpages': maxpages,
        'mywhere': mywhere
    }
    return render(request, "myadmin/member/index.html", context)


def add(request):
    '''加载添加页面'''
    return render(request, 'myadmin/member/add.html')


def insert(request):
    '''执行添加'''
    try:
        #图片的上传处理
        myfile = request.FILES.get("avatar", None)
        print(myfile)
        if not myfile:
            return HttpResponse("没有头像上传文件信息")
        avatar = str(time.time()) + "." + myfile.name.split('.').pop()
        destination = open("./static/uploads/member/" + avatar, "wb+")
        for chunk in myfile.chunks():  # 分块写入文件
            destination.write(chunk)
        destination.close()

        #实例化model，封装信息，并执行添加
        ob = Member()
        ob.nickname = request.POST['nickname']
        ob.mobile = request.POST['mobile']
        ob.avatar = avatar
        ob.status = 1
        ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {"info": "添加成功！"}
    except Exception as err:
        print(err)
        context = {"info": "添加失败"}
    return render(request, "myadmin/info.html", context)


def delete(request, mid):
    '''删除信息'''
    try:
        ob = Member.objects.get(id=mid)
        ob.status = 9
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {"info": "删除成功！"}
    except Exception as err:
        print(err)
        context = {"info": "删除失败"}

    return render(request,"myadmin/info.html",context)


def edit(request, mid):
    '''加载编辑信息页面'''
    try:
        ob = Member.objects.get(id=mid)
        context = {"member": ob}
        return render(request, "myadmin/member/edit.html", context)
    except Exception as err:
        print(err)
        context = {"info": "没有找到要修改的信息！"}
        return render(request, "myadmin/info.html", context)


def update(request, mid):
    '''执行编辑信息'''
    try:
        # #获取原图片名
        # oldpicname = request.POST['oldpicname']
        # #判断是否有文件上传
        # myfile = request.FILES.get("cover_pic", None)
        # if not myfile:
        #     cover_pic = oldpicname
        # else:
        #     #图片的上传处理
        #     cover_pic = str(time.time()) + "." + myfile.name.split('.').pop()
        #     destination = open("./static/uploads/product/" + cover_pic, "wb+")
        #     for chunk in myfile.chunks():  # 分块写入文件
        #         destination.write(chunk)
        #     destination.close()

        ob = Member.objects.get(id=mid)
        ob.nickname = request.POST['nickname']
        ob.mobile = request.POST['mobile']
        ob.status = request.POST['status']
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {"info": "修改成功！"}
    except Exception as err:
        print(err)
        context = {"info": "修改失败"}

    return render(request, "myadmin/info.html", context)